class ReportsController < ApplicationController

  def show
    conditions    =   session['conditions'] 
    sort          =   session['sort'] 
    columns       =   get_selected_columns
    include       =   get_selected_assoc_columns
    
    if conditions != nil and sort != nil 
      data = Document.report_table(:all, 
          :include=> include,
          :conditions => conditions, 
          :order => sort, 
          :only => columns)
    elsif conditions != nil
      data = Document.report_table(:all, 
          :include=> include,
          :conditions => conditions, 
          :only => columns)
    elsif sort != nil 
      data = Document.report_table(:all, 
          :include=> include,
          :order => sort, 
          :only => columns)      
    else
      data = Document.report_table(:all, 
          :include=> include,
          :only => columns)      
    end
    
#          
#     Fix the order of the columns
#     
    column_indices = []
    cols_for_report =[]
    columns.each do |c| 
      unless data.column_names.index(c).nil? 
        column_indices << data.column_names.index(c)
        cols_for_report << c.tr(".", " ").titleize
      end 
    end   
  
    data = data.reorder(column_indices)
    data.column_names =  cols_for_report
    
    respond_to do |format|
      #format.html { self.reset }
      format.csv do
        rpt = File.new( "public/report.csv", "w+" ) 
        rpt.write(  data.as(:csv) )
        rpt.close
        redirect_to "/report.csv", :content_type => "text/csv"
      end
    end
  end
  

  def new
    documents_per_page = 20
    
    if not params[:from_run].nil?
      session['first_run'] = 0
    end
    
    @associations = Document.reflections.values.every(:name)

    @filter_hash = get_hash_filter
    
    sort = case params['sort']
           when "title"  then "title"
           when "title_reverse"  then "title DESC"
           
           when "identifier"   then "identifier"
           when "identifier_reverse"   then "identifier DESC"
           
           when "dated"   then "dated"
           when "dated_reverse"   then "dated DESC"
           
           when "keywords"   then "keywords"
           when "keywords_reverse"   then "keywords DESC"
           
           when "department"   then "departments.name"
           when "department_reverse"   then "departments.name DESC"
           
           when "company"   then "companies.name"
           when "company_reverse"   then "companies.name DESC"
           
           when "person"   then "people.name"
           when "person_reverse"   then "people.name DESC"
           
           when "user"   then "users.username"
           when "user_reverse"   then "users.username DESC"
           end

    conditions = ["#{params[:search_col]} LIKE ?", "%#{params[:query]}%"] unless params[:query].nil?
    session['conditions'] = conditions
    session['sort'] = sort
    
    @total = Document.count(:include=> [:user, :person, :department, :company], 
                            :conditions => conditions)
                            
    @documents_pages, @documents = paginate :documents, 
                            :order => sort, 
                            :include=> [:user, :person, :department, :company], 
                            :conditions => conditions, 
                            :per_page => documents_per_page

    if (params[:from_sort]) or (params[:from_page])
      render :partial => "documents_list"
      session['first_run'] += 1
    elsif session['first_run'] == 0 and params[:from_run]
      if session['select_columns'].nil? 
        render :text => '<p style="color: red; font-weight:bold;">No fields selected - please drag and drop the fields into the grey box</p>'
      else
        render :partial => 'list'
        session['first_run'] += 1
      end
    elsif request.xml_http_request? 
      render :partial => "documents_list"
      session['first_run'] += 1
    else
      self.reset
    end
        
  end
  
  def add_column
    if session['select_columns'].nil?
      session['select_columns'] = []
      session['first_run'] = 0
    end
    session['select_columns'] << params[:id]
    render :text => session['select_columns'].join(", ").titleize
  end
  
  
  def reset
    session['select_columns'] = nil
    session['first_run'] = 0
    session['sort'] = nil
    session['conditions'] = nil
  end
 
  private 
  def get_hash_filter
    if session['select_columns'].nil?
      return
    end
    filter_hash = []
    assoc_names = Document.reflections.values.every(:name).join(",").split(",")
    session['select_columns'].each do |x| 
      if x.in? assoc_names
        new_entry = x == "user" ? ["#{x}", "#{x.pluralize}.username"] : ["#{x}", "#{x.pluralize}.name"]
        filter_hash << new_entry
      else
        filter_hash << ["#{x}","documents.#{x}"] 
      end
    end   
    filter_hash
 end 
 
 def get_selected_columns
    if session['select_columns'].nil?
      return
    end
    selected_columns = []
    assoc_names = Document.reflections.values.every(:name).join(",").split(",")
    session['select_columns'].each do |x| 
      if x.in? assoc_names
        new_entry = x == "user" ? "#{x}.username" : "#{x}.name"
        if x == "company"
          new_entry = eval "#{x.titleize}.column_names"
          new_entry.delete("id") 
          company_cols = new_entry.collect{|x| "company."+x}
          selected_columns = selected_columns + company_cols
        else  
          selected_columns << new_entry
        end  
      else
        selected_columns << "#{x}" 
      end
    end   
    selected_columns
 end 
  
   def get_selected_assoc_columns
    if session['select_columns'].nil?
      return
    end
    assoc_columns = []
    assoc_names = Document.reflections.values.every(:name).join(",").split(",")
    session['select_columns'].each do |x| 
      if x.in? assoc_names
        assoc_columns << x.to_sym
      end
    end   
    assoc_columns
 end 
 
end
